import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
import 'package:flame/palette.dart';
import 'package:flamedemo/component/Background.dart';
import 'package:flamedemo/component/Ball.dart';
import 'package:flamedemo/component/Border.dart';
import 'package:flamedemo/component/MyJoystick.dart';
import 'package:flamedemo/const/Constant.dart';
import 'package:flutter/cupertino.dart';

class MyGame extends FlameGame with HasGameRef, HasCollisionDetection {
  late MyJoystick joystick;
  Ball ball = Ball();
  @override
  Future<void> onLoad() async {
    final Vector2 BALL_POSITION = Vector2(size.x / 2, size.y - BOTTOM);
    joystick = MyJoystick(
        knob: CircleComponent(
            radius: 30, paint: BasicPalette.black.withAlpha(100).paint()),
        background: CircleComponent(
            radius: 50, paint: BasicPalette.white.withAlpha(100).paint()),
        position: Vector2(size.x / 2, size.y - BOTTOM),
        onStartDrag: (v) {
          ball.isStart = false;
        },
        onEndDrag: (v) {
          ball.velocity = v * 5;
          ball.isStart = true;
          results.clear();
        },
        onDragging: (Vector2 ballPos, Vector2 knobPos) {
          ball.position = ballPos;
          myray.origin.setFrom(knobPos);
          myray.direction = (ballPos - knobPos).normalized();
          collisionDetection.raytrace(myray,
              maxDepth: 3,
              out: results,
              ignoreHitboxes: [ball.circleHitbox]).toList();
        });
    ball.position = BALL_POSITION;
    addAll([Background(), MyBorder(), ball]);
    camera.viewport.addAll([joystick]);
  }

  @override
  void render(Canvas canvas) {
    super.render(canvas);
    renderResult(canvas, myray.origin, results, rayPaint);
  }

  void renderResult(Canvas canvas, Vector2 origin,
      List<RaycastResult<ShapeHitbox>> results, Paint paint) {
    var originOffset = origin.toOffset();
    for (final result in results) {
      if (!result.isActive) {
        continue;
      }
      final intersectionPoint = result.intersectionPoint!.toOffset();
      canvas.drawLine(
        originOffset,
        intersectionPoint,
        paint,
      );
      originOffset = intersectionPoint;
    }
  }
}
